package com.hxkcloud.nurse.activitys;

import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hxkcloud.nurse.R;
import com.hxkcloud.nurse.YjhApplication;
import com.hxkcloud.nurse.adapter.TakeDrugsAdapter;
import com.hxkcloud.nurse.beans.DrugBean;
import com.hxkcloud.nurse.beans.DrugsList;
import com.hxkcloud.nurse.beans.TakeDrugsRecordBean;
import com.hxkcloud.nurse.beans.TakeDrugsRecordWholeBean;
import com.hxkcloud.nurse.request.MessageCode;
import com.hxkcloud.nurse.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.nurse.views.pulltorefreshlayout.PullToRefreshLayout;
import com.hxkcloud.nurse.views.pulltorefreshlayout.PullableExpandableListView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by william_sun on 2016-10-06.
 * Description:患者端用药记录列表
 */
public class TakeDrugsActivity extends BaseActivity implements View.OnClickListener, PullToRefreshLayout.OnRefreshListener {

    //title
    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;
    private ImageView iv_add;

    private PullToRefreshLayout refreshLayout;
    private PullableExpandableListView eListView;

    private List<TakeDrugsRecordBean> datas;
    private int totalCount = 0;
    private TakeDrugsAdapter adapter;

    private int pageIndex = 1;
    private int pageSize = 10;

    private List<DrugBean> drugs;//药品列表

//    private String drugId = "";
    private String patientId = "";

    private LinearLayout emptyLayout;
    private TextView emptyTV;

    private DataSetObserver observer = new DataSetObserver() {
        @Override
        public void onChanged() {
            super.onChanged();
        }

        @Override
        public void onInvalidated() {
            super.onInvalidated();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_takedrugs);
//        if (getIntent().hasExtra("drugid")) {
//            drugId = getIntent().getStringExtra("drugid");
//        }
        if (getIntent().hasExtra("patientId")) {
            patientId = getIntent().getStringExtra("patientId");

        } else {
            patientId = loginInfo.getPatientId();
        }
        initView();
        YiJiaHuNetWorkUtils.drugsList(loginInfo.getDepartmentId(), handler);
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_TAKEDRUGSRECORD_SUCCESS:
                TakeDrugsRecordWholeBean wholeBean = (TakeDrugsRecordWholeBean) msg.obj;
                if (pageIndex == 1) {
                    datas.clear();
                    refreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);

                    if (wholeBean.getList().size() > 0) {
                        refreshLayout.setVisibility(View.VISIBLE);
                        emptyLayout.setVisibility(View.GONE);
                    } else {
                        refreshLayout.setVisibility(View.GONE);
                        emptyLayout.setVisibility(View.VISIBLE);
                    }
                } else {
                    refreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                }

                datas.addAll(wholeBean.getList());
                if (!TextUtils.isEmpty(wholeBean.getTotalCount())) {
                    totalCount = Integer.valueOf(wholeBean.getTotalCount());
                }
                adapter.setDatas(datas);
                for (int i = 0; i < datas.size(); i++) {
                    eListView.expandGroup(i);
                }
                break;
            case MessageCode.NETWORKCODE_TAKEDRUGSRECORD_FAILURE:
                if (pageIndex == 1) {
                    refreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                } else {
                    refreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                }
                if (datas != null && datas.size() > 0) {

                } else {
                    if ((msg.obj != null) && (!TextUtils.isEmpty((String) msg.obj))) {
                        toastMsg((String) msg.obj);
                    } else {
                        toastMsg(R.string.datagetfail);
                    }
                }
                break;
            case MessageCode.NETWORKCODE_DRUGSLIST_SUCCESS:
                drugs = (List<DrugBean>) msg.obj;
                break;
        }
    }

    @Override
    protected void initView() {
        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);
        iv_add = (ImageView) findViewById(R.id.iv_title_func);

        setTitlePadding(ll_title);
        iv_back.setVisibility(View.VISIBLE);
        tv_title.setText(getResources().getText(R.string.takedrugrecord));
        iv_add.setVisibility(View.VISIBLE);
        iv_add.setImageResource(R.drawable.nav_add);
        iv_back.setOnClickListener(this);
        iv_add.setOnClickListener(this);

        if (loginInfo.getUserStyle().equals(YjhApplication.userstyle_patient)) {
            iv_add.setVisibility(View.VISIBLE);
        } else {
            iv_add.setVisibility(View.INVISIBLE);
        }

        refreshLayout = (PullToRefreshLayout) findViewById(R.id.refreshlayout_takedrugs);
        eListView = (PullableExpandableListView) findViewById(R.id.recyclerview_takedrugs);

        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setCanPull(true, true);

        datas = new ArrayList<>();

        adapter = new TakeDrugsAdapter(mContext, datas);
        adapter.registerDataSetObserver(observer);
        eListView.setAdapter(adapter);

        eListView.setGroupIndicator(null);

        eListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                if (loginInfo.getUserStyle().equals(YjhApplication.userstyle_patient)) {
                    if (!TextUtils.isEmpty(loginInfo.getDepartmentId())) {
                        DrugsList drugsList = new DrugsList();
                        List<DrugBean> drugBeans = new ArrayList<>();
                        TakeDrugsRecordBean.DrugTime drugTime = datas.get(groupPosition).getList().get(childPosition);
                        for (TakeDrugsRecordBean.DrugTake drugTake : drugTime.getDrugList()) {
                            DrugBean drugBean = null;
                            for (DrugBean drug : drugs) {
                                if (drug.getDrugId().equals(drugTake.getDrugId())) {
                                    drugBean = drug;
                                    drugBean.setSelectDose(drugTake.getDoseId());
                                    break;
                                }
                            }
                            drugBeans.add(drugBean);
                        }
                        drugsList.setList(drugBeans);
                        Intent iModify = new Intent(mContext, AddDrugActivity.class);
                        iModify.putExtra("druglist", (Serializable) drugsList);
                        iModify.putExtra("date", datas.get(groupPosition).getDate());
                        iModify.putExtra("recordid", drugTime.getRecordId());
                        iModify.putStringArrayListExtra("times", (ArrayList) drugTime.getTimeList());
                        startActivity(iModify);
                    } else {
                        toastMsg("暂无药品可选，请先加入科室！");
                    }
                }
                return false;
            }
        });


        emptyLayout = (LinearLayout) findViewById(R.id.ll_department_empty);
        emptyTV = (TextView) findViewById(R.id.empty_text);
        emptyTV.setText(getResources().getString(R.string.empty_text_mydrugs));


    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {
        loading();
       // YiJiaHuNetWorkUtils.takeDrugsRecord(patientId, pageIndex, pageSize,drugId,handler);
        YiJiaHuNetWorkUtils.takeDrugsRecord(patientId, pageIndex, pageSize,handler);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back:
                finish();
                break;
            case R.id.iv_title_func:
                if (!TextUtils.isEmpty(loginInfo.getDepartmentId())) {
                    Intent iAdd = new Intent(mContext, DrugListActivity.class);
                    startActivity(iAdd);
                } else {
                    toastMsg("暂无药品可选，请先加入科室！");
                }
                break;
        }
    }

    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        pageIndex = 1;
        loading();
//        YiJiaHuNetWorkUtils.takeDrugsRecord(patientId, pageIndex, pageSize, drugId, handler);
        YiJiaHuNetWorkUtils.takeDrugsRecord(patientId, pageIndex, pageSize, handler);
    }

    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        int dataSize = 0;
        for (TakeDrugsRecordBean bean : datas) {
            dataSize += bean.getList().size();
        }
        if (dataSize >= totalCount) {
            toastMsg(R.string.nomore);
            refreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
        } else {
            pageIndex++;
            loading();
//            YiJiaHuNetWorkUtils.takeDrugsRecord(patientId, pageIndex, pageSize, drugId, handler);
            YiJiaHuNetWorkUtils.takeDrugsRecord(patientId, pageIndex, pageSize, handler);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        adapter.unregisterDataSetObserver(observer);
    }
}
